component extends="Model" output="false" {

	public void function init() {
	  hasMany('team_players');	  
	  nestedProperties(associations="team_players");
	  afterSave('createTeamPlayerHolders');
	}

	public function createTeamPlayerHolders() {
		var loc = {};			

		loc.queryService = new Query();
		loc.queryService.setName('createTeamPlayerHolders');
		loc.queryService.setDatasource(get('dataSourceName'));
		loc.queryService.addParam(name="teamid",value=this.key(),cfsqltype="cf_sql_integer"); 
		loc.result = loc.queryService.execute(sql="
			IF NOT EXISTS (SELECT COUNT(1) FROM team_players WHERE teamid=:teamid )
			BEGIN
			INSERT INTO team_players (teamid, playerid, pickNo) VALUES (:teamid,0,1);
			INSERT INTO team_players (teamid, playerid, pickNo) VALUES (:teamid,0,2);
			INSERT INTO team_players (teamid, playerid, pickNo) VALUES (:teamid,0,3);
			END");
		return loc.result.getResult();
	}

	public function getTeamPlayersWithPlayerNames(teamId)
	{
		var loc = {};
		loc.queryService = new Query();
		loc.queryService.setName('getPlayersByFixtureId');
		loc.queryService.setDatasource(get('dataSourceName'));
		loc.queryService.addParam(name="teamid",value=teamId,cfsqltype="cf_sql_integer");
		loc.result = loc.queryService.execute(sql="
			SELECT 
				t.id as teamid, 
				tp.id as teamplayerid,
				p.id as playerid,
				t.team_name,
				tp.pickNo,
				p.first_name,
				p.last_name,
				p.avg_fantasy_points
			FROM teams t WITH (NOLOCK)
			INNER JOIN team_players tp WITH (NOLOCK) ON tp.teamid = t.id
			LEFT JOIN players p WITH (NOLOCK) ON tp.playerid = p.id
			WHERE t.id = :teamid
		");
		return loc.result.getResult();
	}

}
